
(import
  (scheme base)
  (scheme read)
  (scheme write)
  (srfi 1)
  (macduffie cipher))

(define puzzle #f)

(define (try-solution key)
  (display (apply-cipher mono-decipher #t puzzle key))
  (newline))

(define (check-input key)
  (define (check-alpha-issues)
    (define a (string->list "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
    (define b (string->list key)) 

    (null? (filter (lambda (s) (not (member s b))) a)))

  (cond
   ((< (string-length key) 26)
    "Input contains less than 26 letters\n")
   ((> (string-length key) 26)
    "Input contains more than 26 letters\n")
   ((not (check-alpha-issues))
    "Input does not contain exactly 1 of each letter\n")
   (else
    #f)))

(define (main)
  (display "Enter the puzzle:\n")
  (set! puzzle (read-line))
  (display "Enter next key to try (leave blank to quit):\n")

  (let loop ()
    (define next-key (read-line))
    (display "\n")
    (when (and (string? next-key)
               (> (string-length next-key) 0))
      (let ((input-error (check-input next-key)))
        (if input-error
            (display input-error)
            (try-solution next-key))
        (display "Enter next key to try: (leave blank to quit)\n")
        (loop)))))

(main)
